import Vue from 'vue'
import { getUserInfo } from '@/utils/user'
import { getEnv } from '@/utils/buffer'
import { computeStartPath } from './scheme'
import { shareAward } from '@/api/system'

/**
 * 获取分享给好友路径
 * @param {String} title
 * @param {String} type
 * @param {String} id
 */
export function getShareAppData(desc = '', title = 'Aha口袋') {
  const inviteUserId = getUserInfo().userInfo.userId

  let path = computeStartPath()

  /* 加入邀请人id */
  if (path.indexOf('?') > 1) {
    path += `&inviteUserId=${ inviteUserId }`
  } else {
    path += `?inviteUserId=${ inviteUserId }`
  }
  console.log(path)

  /* 调用分享奖励接口 */
  shareAward()
  return {
    title,
    desc,
    path,
  }
}

/**
 * 复制到剪切板，并提示文字
 * @param {String}  content 复制内容
 * @param {String}  msg 提示文字
 */
export function copyData(content, msg) {
  uni.setClipboardData({
    data: String(content),
    success: () => {
      if (msg) {
        Vue.prototype.$msg(msg)
      }
    },
    fail: (err) => {
      console.log(err)
      Vue.prototype.$error('复制错误..')
    }
  })
}

/**
 * 路径转对象
 */
export function urlToObj(url = '') {
  const obj = {}

  const str = url.split('?')[ 1 ]

  if (str) {
    str.split('&').forEach(item => {
      item = item.split('=')
      obj[ item[ 0 ] ] = item[ 1 ]
    })
  }
  return obj
}

/**
 * 根据环境变量获取文件名，测试环境文件名前加/test
 */
export function getFilename(name) {
  return getEnv().name === 'release' ? name : 'test/' + name
}

/**
 * 根据时间差转化成 几日，几时，几分，几秒
 * @param {Number} time 时间戳
 */
export function formatDiffTime(time) {
  if (typeof time === 'number') {
    const date = {
      day: 0,
      hour: 0,
      minute: 0,
      seconds: 0,
      millisecond: 0
    }

    /* 日 */
    date.day = Math.floor(time / (24 * 60 * 60 * 1000))
    time = time - date.day * (24 * 60 * 60 * 1000)
    /* 时 */
    date.hour = Math.floor(time / (60 * 60 * 1000))
    time = time - date.hour * (60 * 60 * 1000)
    /* 分 */
    date.minute = Math.floor(time / (60 * 1000))
    time = time - date.minute * (60 * 1000)
    /* 秒 */
    date.seconds = Math.floor(time / (1000))
    date.millisecond = time - date.seconds * (1000)

    return date
  } else {
    console.error('时间差转换失败：入参错误')
    return {}
  }
}

/**
 * 订阅消息
 */
export async function subWxMessage(tmplIds = []) {
  const subRes = await wx.requestSubscribeMessage({
    tmplIds,
  })

  if (subRes.NbYQnYQenPYrch07DOgDHUOkjvwnrQw3OVypEqokXpI === 'accept') {
    return true
  } else {
    return false
  }
}

/**
 * 返回不为undefined的值
 */
export function filterVal(...values) {
  return values.find(item => item !== undefined)
}

/**
 * 判断项目类型
 */
export function getProjectTypeById(projectId) {
  if (projectId < 50000000) {
    return 'competition'
  }
  return 'courseDesign'
}
